package com.yenlien.traceyun.plant.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.dao.*;
import com.yenlien.traceyun.business.entity.StorageManage;
import com.yenlien.traceyun.business.entity.Subpackage;
import com.yenlien.traceyun.business.entity.WarehouseIn;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.StorageManageCuringService;
import com.yenlien.traceyun.business.service.StorageManageService;
import com.yenlien.traceyun.business.service.SubpackageService;
import com.yenlien.traceyun.business.trace.TraceService;
import com.yenlien.traceyun.plant.bean.Out;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by LiuSha on 2020/7/29.
 */
@Service
public class PlantStorageManageService {
    @Autowired
    private StorageManageDao storageManageDao;
    @Autowired
    private StorageManageDetailedDao storageManageDetailedDao;
    @Autowired
    private StorageManageCuringService storageManageCuringService;

    @Autowired
    private ProcessDetailDao processDetailDao;

    @Autowired
    private WarehouseInDao warehouseInDao;

    @Autowired
    private SubpackageDao subpackageDao;

    @Autowired
    private SubpackageService subpackageService;

    @Autowired
    private StorageManageService storageManageService;

    @Autowired
    private TraceService traceService;

    @Value("${traceyun.app.id}")
    private String appId;

    /**
     * 入库
     *
     * @param storageManages
     * @param subpackage
     * @param codes
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void save(List<StorageManage> storageManages, Subpackage subpackage, List<String> codes) {
        if (storageManages != null && storageManages.size() > 0) {
            String companyId = UserAuthUtil.getLoginUser().getCompanyId();
            for (StorageManage storageManage : storageManages) {
                storageManage.setCompanyId(companyId);
                StorageManage p = storageManageService.in(storageManage);
                //分包入库
                if (storageManage.getInType().equals("1")) {
                    subIn(p);
                }
                //采购入库
                else if (storageManage.getInType().equals("0")) {
                    purchaseIn(storageManage, subpackage, codes);
                } else {
                    throw new BusinessException("500", "intype类型不对");
                }
            }
        }
    }


    /**
     * 分包入库
     *
     * @param storageManage
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void subIn(StorageManage storageManage) {
        WarehouseIn in = new WarehouseIn();
        in.setCode(storageManage.getSourceBatch());
        in.setCodeType("1");
        in.setInType(storageManage.getInType());
        in.setStorageManageId(storageManage.getId());
        warehouseInDao.save(in);
    }

    /**
     * 采购入库
     */
    public void purchaseIn(StorageManage storageManage, Subpackage subpackage, List<String> codes) {

        //溯源入库
        if (storageManage.getPurchaseType().equals("0")) {
            //追溯码管理
            if (codes != null && codes.size() > 0) {
                List<WarehouseIn> warehouseIns = new ArrayList<>();
                for (String item : codes) {
                    WarehouseIn initem = new WarehouseIn();
                    initem.setInType(storageManage.getInType());
                    initem.setStorageManageId(storageManage.getId());
                    initem.setCodeType("1");
                    warehouseIns.add(initem);
                }
                warehouseInDao.saveAll(warehouseIns);
            }
        } else {
            subpackage.setSource("采购分包");
            subpackage.setRelevanceId(storageManage.getId());
            subpackage.setLastStep(storageManage.getId());
            subpackage.setProductName(storageManage.getProductName());
            subpackage.setSpec(storageManage.getSpecs() + "");
            subpackage.setSpecUnits(storageManage.getSpecsUnit());
            subpackage.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
            subpackage.setAppId(appId);
            subpackage.setBatch(storageManage.getId());
            Subpackage p = subpackageService.subAndGenreateCode(subpackage);

            WarehouseIn in = new WarehouseIn();
            in.setInType(storageManage.getInType());
            in.setStorageManageId(storageManage.getId());
            in.setCode(p.getId());
            //批次管理
            in.setCodeType("0");
            warehouseInDao.save(in);
        }
    }


    @Transactional
    public void out(Out out) {
        Set<String> orderIds = new HashSet<>();
        if (out.getOrderDetaileds() != null && out.getOrderDetaileds().size() > 0) {
//            for (OrderDetailed orderDetailed : out.getOrderDetaileds()) {
//                Order order = orderDao.findById(orderDetailed.getOrderId());
//                orderDetailed.setIsOut(1);
//                orderDetailed.setDriver(out.getDriver());
//                orderDetailed.setCarCode(out.getCarCode());
//                orderDetailed.setPhone(out.getPhone());
//                orderDetailed.setLogistics(out.getLogistics());
//                orderDetailed.setLogisticsCode(out.getLogisticsCode());
//                orderDetailedDao.save(orderDetailed);
//                StorageManage storageManage = storageManageDao.findById(orderDetailed.getStorageId());
//                if(DataUtil.subtractDecimal(orderDetailed.getNumber(),storageManage.getSurplus()).compareTo(BigDecimal.ZERO)>0){
//                    throw new BusinessException("Z001", storageManage.getProductName() + "库存数量不足" + orderDetailed.getNumber());
//                }
//
//                storageManage.setSurplus(Tools.subtr(storageManage.getSurplus(), orderDetailed.getNumber()));
//                storageManageDao.save(storageManage);
//                StorageManageDetailed storageManageDetailed = new StorageManageDetailed();
//                storageManageDetailed.setStorageManageId(storageManage.getId());
//                storageManageDetailed.setNumber(orderDetailed.getNumber());
//                storageManageDetailed.setSpecs(orderDetailed.getSpecs());
//                storageManageDetailed.setUnit(storageManage.getUnit());
//                storageManageDetailed.setTraceCode(orderDetailed.getTraceCode());
//                storageManageDetailed.setType("出库");
//                storageManageDetailed.setClientName(order.getClientName());
//                storageManageDetailed.setCreatetime(new Date());
//                storageManageDetailedDao.save(storageManageDetailed);
//                orderIds.add(orderDetailed.getOrderId());
//            }
//        }
//        if (orderIds.size() > 0) {
//            for (String orderId : orderIds) {
//                Order order = orderDao.findById(orderId);
//                order.setState("3");
//                if (out.getType().equals("物流车")) {
//                    order.setLogistics(order.getLogistics() + "司机:" + out.getDriver() + ";车牌:" + out.getCarCode() + ";电话:" + out.getPhone());
//                } else {
//                    order.setLogistics(order.getLogistics() + "物流:" + out.getLogistics() + ";物流单号:" + out.getLogisticsCode());
//                }
//                orderDao.save(order);
//            }
//        }
        }
    }


    public void adjustment(JSONObject jsonObject) {
        String id = jsonObject.getString("storageId");
        String actualNum = jsonObject.getString("actualNum");
        String remarks = jsonObject.getString("remarks");
        StorageManage storageManage = storageManageDao.findById(id);
//        storageManage.setSurplus(actualNum);

        storageManageDao.save(storageManage);
    }

    public StorageManage findById(String id) {
        StorageManage storageManage = storageManageDao.findById(id);
        storageManage.setStorageManageDetaileds(storageManageDetailedDao.findByStorageManageId(id));
        storageManage.setStorageManageCuringList(storageManageCuringService.findByStorageManageId(id));
        return storageManage;
    }


}
